package com.data.hijack.http;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import com.data.hijack.util.StringUtils;

public class DefaultTempFileManager implements ITempFileManager {

    private final File tmpdir;

    private final List<ITempFile> tempFiles;

    public DefaultTempFileManager(String tmpDir) {
        String dir = System.getProperty("java.io.tmpdir");
        if (StringUtils.isNotBlank(tmpDir)) {
            dir = tmpDir;
        }

        this.tmpdir = new File(dir);
        if (!tmpdir.exists()) {
            tmpdir.mkdirs();
        }
        this.tempFiles = new ArrayList<ITempFile>();
    }

    @Override
    public void clear() {
        for (ITempFile file : this.tempFiles) {
            try {
                file.delete();
            } catch (Exception ignored) {
                ignored.printStackTrace();
                System.out.println(Level.WARNING + "could not delete file ");
            }
        }
        this.tempFiles.clear();
    }

    @Override
    public ITempFile createTempFile(String filename_hint) throws Exception {
        DefaultTempFile tempFile = new DefaultTempFile(this.tmpdir, filename_hint);
        this.tempFiles.add(tempFile);
        return tempFile;
    }
}
